package com.bw.good.vm

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.bawei.common.vm.BaseViewModel
import com.bw.good.entity.GoodEntity
import com.bw.good.intent.GoodViewIntent
import com.bw.good.model.GoodRepository
import com.bw.good.state.GoodUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class GoodViewModel @Inject constructor(private val repository: GoodRepository): BaseViewModel<GoodViewIntent>() {

    private val _uiState = MutableStateFlow<GoodUiState>(GoodUiState.LoadEmpty)
    val uiState: StateFlow<GoodUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: GoodViewIntent) {
        when(intent) {
            is GoodViewIntent.LoadGoodList -> loadGoodList(intent.categoryId,intent.currentPage,intent.pageSize)
        }
    }

    private fun loadGoodList(categoryId: Int, currentPage: Int, pageSize: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                repository.loadGoodList(categoryId, currentPage, pageSize).collect {
                    withContext(Dispatchers.Main) {
                        if (it.isNotEmpty()) {
                            _uiState.value = GoodUiState.LoadGoodListSuccess(it)
                        } else {
                            _uiState.value = GoodUiState.LoadGoodListFail("没有商品列表数据")
                        }
                    }
                }
            } catch (e:java.lang.Exception) {
                e.printStackTrace()
                _uiState.value = GoodUiState.LoadGoodListFail("请求失败!!")
            } finally {
                cancel()
            }
        }
    }


}